#!/bin/bash
#set -x
set -e

# 备份配置
MONGO_HOST='127.0.0.1'
MONGO_PORT='27017'
MONGO_USER='admin'
MONGO_PASSWORD='admin123'
MONGO_AUTH_DB='admin'
BACKUP_DIR='/data/mongodb/backup'
BACKUP_DBS=(
  'admin'
  'db1'
  'db2'
)
BACKUP_TMP_DIR='/data/mongodb/backup_tmp'

# 内部的变量
echoPrefix="\033[36m+"
echoSuffix="\033[0m"
date=$(date +%Y%m%d_%H%M%S)
tmp_dir="$BACKUP_TMP_DIR/$date"

# 创建备份目录
echo -e "$echoPrefix mkdir -p $BACKUP_DIR $echoSuffix"
mkdir -p "$BACKUP_DIR"

echo -e "$echoPrefix mkdir -p $tmp_dir $echoSuffix"
mkdir -p "$tmp_dir"

# 备份数据
for ((idx=0; idx<${#BACKUP_DBS[@]}; idx++)); do
    db_name="${BACKUP_DBS[idx]}"
    echo -e "开始备份数据库: $db_name"
    echo -e "$echoPrefix mongodump -v --host=$MONGO_HOST --port=$MONGO_PORT -u=admin -p='$MONGO_PASSWORD' --authenticationDatabase=$MONGO_AUTH_DB --db=$db_name --out $tmp_dir --gzip $echoSuffix"
    mongodump -v --host=$MONGO_HOST --port=$MONGO_PORT -u=admin -p=$MONGO_PASSWORD --authenticationDatabase=$MONGO_AUTH_DB --db=$db_name --out $tmp_dir --gzip
    if [ $? -eq 0 ]; then
        echo -e "备份成功: $db_name"
        # 删除上一次的备份
        echo -e "$echoPrefix rm -rf $BACKUP_DIR/$db_name $echoSuffix"
        rm -rf "$BACKUP_DIR/$db_name"
        # 替换上一次的备份
        echo -e "$echoPrefix mv $tmp_dir/$db_name $BACKUP_DIR $echoSuffix"
        mv "$tmp_dir/$db_name" $BACKUP_DIR
        echo "备份文件替换成功: $db_name"
    else
        echo -e "备份失败: $db_name"
    fi
done

# 删除临时目录
echo -e "$echoPrefix rmdir $tmp_dir $echoSuffix"
rmdir "$tmp_dir"
